﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Management;
using MSHTML;
using System.Net;
using System.IO;
using System.Web;
using System.Text.RegularExpressions;
using System.Runtime.InteropServices;
using System.Threading;
using System.Diagnostics;
using Microsoft.Win32;

namespace Givenchy
{
    class Helper
    {
        const int BUFFER_SIZE = 1024;
        
        /// <summary>
        /// 分析脚本信息
        /// </summary>
        /// <param name="script"></param>
        /// <returns></returns>
        public static List<BrowserAction> executeScript(string script)
        {
            string[] webactions = Regex.Split(script, @"\|\|", RegexOptions.IgnoreCase);

            List<BrowserAction> result = new List<BrowserAction>();

            foreach (string obj in webactions)
            {
                string[] wa = obj.Split(',');
                //println "${id}  ${wa[0]} ${wa[1]} ${wa.size() > 2? wa[2] :''}" 
                if (wa.Length > 1)
                {
                    result.Add(new BrowserAction(
                         wa[0].Trim(),
                         wa[1].Trim(),
                         wa.Length > 2 ? wa[2].Trim() : ""
                    ));
                }
                Application.DoEvents();
            }
            return result;
        }
        /// <summary>
        /// C# HTTP Request请求程序模拟 向服务器送出请求 
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string SendRequest(string url)
        {
            if (url.Contains("?"))
            {
                url = url + "&" + System.DateTime.Now.Millisecond.ToString();
            }
            else
            {
                url = url + "?" + System.DateTime.Now.Millisecond.ToString();
            }
            try
            {
                SimpleWebRequest awr = new SimpleWebRequest();
                return awr.send(url);
            }
            catch (WebException)
            {

            }
            return "";

        }


        /// <summary>
        /// 清理信息
        /// </summary>
        public static void clear()
        {

            KillIEWindows();
            ClearCookies();
            ClearIECache();
            ClearIECookie();
        }
        /// <summary>
        /// 获得mac地址
        /// </summary>
        /// <returns></returns>
        public static string GetMacAddress()
        {
            ManagementClass adapters = new ManagementClass("Win32_NetworkAdapterConfiguration");
            string MACAddress = "unknown";
            foreach (ManagementObject adapter in adapters.GetInstances())
            {
                if ((bool)adapter["IPEnabled"] == true)
                {
                    MACAddress = adapter.Properties["MACAddress"].Value.ToString();
                    break;
                }
                Application.DoEvents();
            }
            return MACAddress;
        }

        private static string IEVersion;
        public static int getIEVersion()
        {

            IEVersion = GetRegValue("\\HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Internet Explorer\\",
               "version").ToString();
            if (IEVersion.StartsWith("6"))
            {
                return 6;
            }
            else if (IEVersion.StartsWith("8"))
            {
                return 8;
            }
            return 0;

        }
        /// <summary>
        /// 从注册表读取信息,第三个参数【不填=是读取，填null=删除，填内容=写入】
        /// </summary>
        /// <param name="strRegPath">路径</param>
        /// <param name="strName">值名</param>
        /// <returns>数据</returns>
        public static string GetRegValue(string strRegPath, string strName, string value = "")
        {
            strRegPath = strRegPath.Trim();
            //接收值的对象  
            object objRet = null;

            // 如果名称为空，则抛出一个参数为空的异常。   
            if (strName == "")
            {
                throw new ArgumentNullException(strName, "键值不能为空!");
            }

            //去除"\"字符
            if (strRegPath.StartsWith("\\"))
            {
                strRegPath = strRegPath.Substring(1, strRegPath.Length - 1);
            }
            if (strRegPath.EndsWith("\\"))
            {
                strRegPath = strRegPath.Substring(0, strRegPath.Length - 1);
            }


            //拆分根键和路径   
            string strRootKey, strPath;
            int intIndex = strRegPath.IndexOf("\\");

            strRootKey = strRegPath.Substring(0, intIndex).ToUpper();

            strPath = strRegPath.Substring(intIndex + 1, strRegPath.Length - intIndex - 1);
            RegistryKey _root;
            switch (strRootKey)
            {
                case "HKEY_CLASSES_ROOT":
                    _root = Registry.ClassesRoot;
                    break;
                case "HKEY_CURRENT_CONFIG":
                    _root = Registry.CurrentConfig;
                    break;
                case "HKEY_CURRENT_USER":
                    _root = Registry.CurrentUser;
                    break;
                //case "HKEY_DYN_DATA":
                //    _root = Registry.DynData;
                //    break;
                case "HKEY_LOCAL_MACHINE":
                    _root = Registry.LocalMachine;
                    break;
                case "HKEY_PERFORMANCE_DATA":
                    _root = Registry.PerformanceData;
                    break;
                case "HKEY_USERS":
                    _root = Registry.Users;
                    break;
                default:
                    throw new Exception("找不到路径!");
            }

            try
            {

                //取值
                if (value == "")
                {
                    //打开注册表路径的键    
                    RegistryKey regKey = _root.OpenSubKey(@strPath);
                    objRet = regKey.GetValue(strName);
                }
                else if (value == null)
                {
                    RegistryKey regKey = _root.OpenSubKey(@strPath, true);
                    regKey.DeleteValue(strName);//删除swort的值   这个连键值一起删除了 剩下一个
                    regKey.DeleteSubKey(strName, false);//删除swort这个目录   要删除这个目录 必须具有权限 
                    return "Delete " + strName + " Successful";
                }
                else
                {
                    RegistryKey regKey = _root.OpenSubKey(@strPath, true);
                    regKey.SetValue(strName, value);
                    return "Write Successful";
                }


            }
            catch (Exception e)
            {
                throw e;
            }
            if (objRet == null)
            {
                return "";
            }
            return objRet.ToString();
        }
        // --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
        /// <summary>
        /// 关闭IE窗口
        /// </summary>
        private static void KillIEWindows()
        {
            Process[] process = Process.GetProcesses();
            for (int i = 0; i < process.Length; i++)
            {
                if (process[i].ProcessName.ToLower() == "iexplore")
                {
                    try
                    {
                        process[i].Kill();
                        process[i].Close();
                        Application.DoEvents();
                        Thread.Sleep(300);
                    }
                    catch
                    {
                    }
                }

            }
        }

        private static void ClearCookies()
        {
            DirectoryInfo dir = new DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.Cookies));
            foreach (FileInfo info in dir.GetFiles("*.txt"))
            {
                info.Delete();
                Application.DoEvents();
            }
        }
        /// <summary>
        /// 清除IE缓存
        /// </summary>
        private static void ClearIECache()
        {
            Process process = new Process();
            process.StartInfo.FileName = "cmd.exe";
            process.StartInfo.Arguments = "/c " + "del /f /s /q \"%userprofile%\\Local Settings\\Temporary Internet Files\\*.*\"";
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.RedirectStandardInput = true;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.RedirectStandardError = true;
            process.StartInfo.CreateNoWindow = true;
            process.Start();
            Application.DoEvents();
            //string result = process.StandardOutput.ReadToEnd();
        }
        // --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

        // --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
        /// <summary>
        /// 清除IE Cookie
        /// </summary>
        private static void ClearIECookie()
        {
            Process process = new Process();
            process.StartInfo.FileName = "cmd.exe";
            process.StartInfo.Arguments = "/c " + "del /f /s /q \"%userprofile%\\Cookies\\*.*\"";
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.RedirectStandardInput = true;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.RedirectStandardError = true;
            process.StartInfo.CreateNoWindow = true;
            process.Start();
            Application.DoEvents();
            //string result = process.StandardOutput.ReadToEnd();
        }
    }



}
